#ifndef __ILIB_CORE_EVENT_H_20120203__
#define __ILIB_CORE_EVENT_H_20120203__

#include "../../iHeader.h"

#if defined(__WIN__)
    typedef HANDLE os_event_t;
#elif defined(__LINUX__)
    #include <pthread.h>
    typedef pthread_cond_t os_event_t;
#endif

class iEvent
{
public:
	iEvent() 
    {
        #if defined(__WIN__)
        m_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
        #elif defined(__LINUX__)
        pthread_mutex_init(&m_mutex, NULL);
        pthread_cond_init(&m_handle, NULL);
        #endif
    }
	void reset()  
    {
        #if defined(__WIN__)
        ResetEvent(m_handle);
        #elif defined(__LINUX__)
        pthread_mutex_lock(&m_mutex);
        m_signaled = false;
        pthread_mutex_unlock(&m_mutex);
        #endif
    }
	void signal() 
    {
        #if defined(__WIN__)
        SetEvent(m_handle); 
        #elif defined(__LINUX__)
        pthread_mutex_lock(&m_mutex);
        m_signaled = true;
        pthread_mutex_unlock(&m_mutex);

        pthread_cond_signal(&m_handle);
        #endif
    }
	uint32_t wait(uint32_t ms) 
    {
        #if defined(__WIN__)
        return WaitForSingleObject(m_handle, ms);
        #elif defined(__LINUX__)
        pthread_mutex_lock(&m_mutex);
        if(m_signaled)
        {
            pthread_mutex_unlock(&m_mutex);
            return 1;
        }
        else
        {
            int ret = 0;
            timespec ts;
            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += ms/1000;
            ts.tv_nsec += (ms%1000) * 1000;
            ret = pthread_cond_timedwait(&m_handle, &m_mutex, &ts);
            pthread_mutex_unlock(&m_mutex);
            return ret==ETIMEDOUT ? 0:1;
        }
        #endif
    }

private:

	os_event_t	m_handle;

#if defined(__LINUX__)
    bool m_signaled;
    pthread_mutex_t m_mutex;
#endif
};

#endif  //__ILIB_CORE_EVENT_H_20120203__
